import { loadGLTFObject } from '../../assets/loader/gltf/gltfParse';
import { Matrix4 } from '../../core/math/Matrix4';
/**
 * @class
 * @memberof w.parser
 * @param {*} message 消息
 * @param {*} callback 处理完成的回调
 */
async function glb(message, callback) {
  const path = message.path
  const matrix = new Matrix4()
  // const matrix =message.matrix
  fetch(message.path).then(result => {
    if (!result.ok) {
      console.error("不能加载瓦片 : " + path)
      throw new Error(`不能加载 "${path}". 加载状态 ${result.status} : ${result.statusText}`);
    }
    return result.arrayBuffer();

  }).then(async arrayBuffer => {
    const glbBytes = new Uint8Array(arrayBuffer);
    const gltfBuffer = glbBytes.slice().buffer;
    const jsonLength = new Uint32Array(gltfBuffer, 12, 1)[0];
    const jsonChunk = new Uint8Array(gltfBuffer, 20, jsonLength);
    const json = JSON.parse(new TextDecoder("utf-8").decode(jsonChunk));
    let options = { optimize: true, matrix, json, url: path, glb: gltfBuffer, glbOffset: 28 + jsonLength }
    let gltfObject = await loadGLTFObject(options);
    let transferlist = gltfObject.transferlist
    // for (let index = 0; index < gltfObject.images.length; index++) {
    //   const image = gltfObject.images[index];
    //   transferlist.push(image.data.buffer)
    // }
    // transferlist.push(...gltfObject.images)
    delete gltfObject.transferlist
    delete gltfObject.buffers
    delete gltfObject.json
    delete gltfObject.meshes
    delete gltfObject.nodes
    delete gltfObject.scenes
    delete gltfObject.worldMatrix
    callback({ data: gltfObject, transferlist: transferlist });
  })


}
export { glb }